import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入需要的路由组件
import Login from '@/views/Login/Login.vue'
import Main from '@/views/Main/Main.vue'
import Home from '@/views/Home/Home.vue'
import User from '@/views/User/User.vue'
import Search from '@/views/Search/Search.vue'
import SearchResult from '@/views/SearchResult/SearchResult.vue'
import ArticleDetail from '@/views/ArticleDetail/ArticleDetail.vue'
import UserEdit from '@/views/UserEdit/UserEdit.vue'
import Chat from '@/views/Chat/Chat.vue'
// 导入store
import store from '@/store/index.js'

// 1. 将 VueRouter 本身提供的 $router.push 方法转存到常量中
const originalPush = VueRouter.prototype.push
// 2. 自定义 $router.push 方法，在内部调用原生的 originalPush 方法进行路由跳转；并通过 .catch 捕获错误
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  // 通过 .catch 捕获错误
  return originalPush.call(this, location).catch(err => err)
}


Vue.use(VueRouter)

const routes = [
  // 登录组件路由规则，带name是命名路由
  {
    path: '/login',
    component: Login,
    name: 'login'
  },
  {
    path: '/',
    component: Main,
    children: [
      // 首页子路由(路径为空，表示默认子路由)
      { path: '', component: Home, name: 'home', meta: { top: 0, isRecordTop: true } },
      // 我的子路由
      { path: 'user', component: User, name: 'user' }
    ]
  },
  {
    path: '/search',
    component: Search,
    name: 'search'
  },
  // 搜索结果页的路由规则
  // this.$route.params.kw可以传参
  {
    path: '/search/:kw',
    component: SearchResult,
    name: 'search-result',
    props: true
  },
  // 文章详情路由
  {
    path: '/article/:id',
    component: ArticleDetail,
    name: 'art-detail',
    props: true
  },
  // 编辑用户资料路由
  {
    path: '/user/edit',
    component: UserEdit,
    name: 'user-edit'
  },
  // 小思同学路由
  {
    path: '/chat',
    component: Chat,
    name: 'chat'
  }
]

const router = new VueRouter({
  routes
})

// 声明全局前置守卫
// pathArr存放的所有有权限的地址
const pathArr = ['/user', '/user/edit']
router.beforeEach((to, from, next) => {
  // 判断from中是否包含元信息
  if (from.meta.isRecordTop) {
    // 把滚动条纵向位置，记录在meta。top中
    from.meta.top = window.scrollY
  }
  if (pathArr.indexOf(to.path) !== -1) {
    // 访问的是有权限的页面
    // 1.从vuex中获取token
    const tokenStr = store.state.tokenInfo.token
    // 判断token是否存在
    // 如果存在，直接方形，否则跳到登录页
    if (tokenStr) {
      // 登录了，直接方形
      next()
    } else {
      // 未登录，强制跳转登录页
      // to这个对象，表示访问未遂的路有对象
      next('/login?pre=' + to.fullpath)
    }
  } else {
    // 直接方行
    next()
  }
})

export default router
